package cn.toleo.order.intercepter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.toleo.common.pojo.ToleoResult;
import cn.toleo.pojo.TbUser;
import cn.toleo.sso.service.UserService;
import cn.toleo.utils.CookieUtils;
/**
 * 判断用户是否登录的拦截器
 * @author Administrator
 *
 */

public class LoginInterceptor implements  HandlerInterceptor{
//-------------------------------------------------------------------------------------------------------------------
	@Value("${TOKEN_KEY}")
	private String TOKEN_KEY;
	@Value("${SSO_URL}")
	private String SSO_URL;
	@Autowired
	private UserService userService;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//主干基础
		String token = CookieUtils.getCookieValue(request, TOKEN_KEY);
		//取不到token,跳转到登录页面
		if(StringUtils.isBlank(token)){
			String requestURL = request.getRequestURL().toString();
			response.sendRedirect(SSO_URL+"/page/login?url="+requestURL);
			return false;
		}
		//取到token,1未登录跳登录 2登录放行
		ToleoResult userByToken = userService.getUserByToken(token);
		if(userByToken.getStatus()!=200){
			String requestURL = request.getRequestURL().toString();
			response.sendRedirect(SSO_URL+"/page/login?url="+requestURL);
			return false;
		}
		TbUser user = (TbUser)userByToken.getData();
		request.setAttribute("user", user);
		// 结果 
		return true;
	}
	
	
	//-------------------------------------------------------------------------------------------------------------------

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
